// pages/profile/profile.js
const app = getApp()
var store = require("../../utils/storageUtil.js")
const constant = require("../../constant.js")
const storage = require("../../utils/storage.js")

Page({

  /**
   * 页面的初始数据
   */
  data: {
    qiniu: constant.resource.qiniu,
    host: constant.api(app.globalData.pord).url,
    unionid: wx.getStorageSync(storage.keys.unionid),
    username: 'hello',
    img: '',
    qiniu: constant.resource.qiniu,
    survey: true,
    showpopup: false,
    hasCoupon: false,
    showCard: false
  },

  cardSignin: function () {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        that.validateSignin(res.result);
      }
    })
  },

  validateSignin: function(message) {
    var that = this;
    that.data.message = message;
      wx.showModal({
        title: '签到',
        content: '是否确认签到？',
        success: function () {
          that.signin(that.data.message);
        }
      })
  },

  signin: function(message) {
    var that = this;
    let unionid = wx.getStorageSync(storage.keys.unionid);
    wx.request({
      url: that.data.host + '/signin/rounds/' + that.data.cardId + '/confirm?unionid=' + unionid + '&message=' + message,
      method: 'GET',
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.code == "0") {
          wx.navigateTo({
            url: '../../pages/user-course/course-round-signin-success/course-round-signin-success?roundId=' + that.data.cardId
          })
        } else {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 3000,
            mask: true
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '签到失败',
          icon: 'none',
          duration: 3000,
          mask: true
        })
      }
    });
  },

  onPopupClose: function (e) {
    this.setData({
      showpopup: false
    })
  },
  chooseDate: function (e) {
    var that = this;
    // this.setData({
    //   chooseDay: e.currentTarget.dataset.date
    // })
    if (e.currentTarget.dataset.schedule) {

      //console.log(e.currentTarget.dataset.date)
      wx.request({
        url: constant.api(app.globalData.pord).url + '/profile/course-schedules/day/' + e.currentTarget.dataset.date + '?unionid=' + wx.getStorageSync(storage.keys.unionid),
        method: 'GET',
        dataType: 'json',
        responseType: 'text',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          if (res.data.code == "0") {
            // that.setData({
            //   modalSchedules: res.data.data.courseSchedules,
            //   showpopup: true
            // })
            if(res.data.data.courseSchedules != null && res.data.data.courseSchedules != undefined  && res.data.data.courseSchedules.length > 1) {
              that.setData({
                  modalSchedules: res.data.data.courseSchedules,
                  showpopup: true
                })
            } else {
              wx.navigateTo({
                url: "/pages/user-course/user-course-detail/course-schedule/course-schedule-detail/course-schedule-detail?scheduleId=" + e.currentTarget.dataset.schedule
  
              })
            }

          } else {
            wx.navigateTo({
              url: "/pages/user-course/user-course-detail/course-schedule/course-schedule-detail/course-schedule-detail?scheduleId=" + e.currentTarget.dataset.schedule

            })
          }
          // debugger
          // that.setData({
          //   days: res.data,
          // });
          // console.log(res.data)
          // var i;
          // var tmp = false;

          // for (i = 0; i < res.data.length; i++) { 
          //   console.log(res.data[i].a )
          //   // text += cars[i] + "<br>";
          //   if (res.data[i].a == 1){
          //     tmp = true;
          //   }
          // }
          // if (tmp) {
          //   that.setData({
          //     days_true: true,
          //   });
          // } else {
          //   that.setData({
          //     days_true: false,
          //   });
          // }


        },
        fail: function (res) {
          // wx.showToast({
          //   title: '请求数据失败',
          //   icon: 'none',
          //   duration: 1000
          // });

          wx.navigateTo({
            url: "/pages/user-course/user-course-detail/course-schedule/course-schedule-detail/course-schedule-detail?scheduleId=" + e.currentTarget.dataset.schedule

          })
        }
      })
      // wx.navigateTo({
      //   url:"/pages/user-course/user-course-detail/course-schedule/course-schedule-detail/course-schedule-detail?scheduleId="+e.currentTarget.dataset.schedule

      // })
    }

  },
  adddetial: function () {
    wx.showToast({
      title: '点击成功',
      icon: 'success',
      duration: 2000
    })
    var text = this.data.username
    var head = this.data.userInfo.avatarUrl
    var student = this.data.student_id

    wx.showActionSheet({
      itemList: ['用自己的图', '随机生成'],
      success: function (res) {
        console.log(res.tapIndex)

        console.log(text)
        if (res.tapIndex == 0) {
          wx.chooseImage({
            count: 1,
            success(res) {
              const tempFilePaths = res.tempFilePaths
              wx.uploadFile({
                url: constant.api(app.globalData.pord).url + '/xh/api/file/upload/', //仅为示例，非真实的接口地址
                filePath: tempFilePaths[0],
                name: 'file',
                success(res) {
                  const data = res.data
                  console.log(data)
                  wx.navigateTo({
                    url: 'share/share?name=' + text + '&img=' + data + '&head=' + head + '&student=' + student
                  })
                  //do something
                }
              })
            }
          })
        } else {
          wx.navigateTo({
            url: 'share/share?name=' + text + '&head=' + head + '&student=' + student
          })
        }
      },
      fail: function (res) {
        console.log(res.errMsg)
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //wx.setStorageSync(storage.keys.unionid, "oecU40g5dW0CaORH-tCiF-_nApvA")
    // console.log(this.globalData.userInfo);
    //获取用户信息

    var that = this;
    wx.getUserInfo({
      success: function (res) {

        console.log(res.userInfo.avatarUrl);
        that.data.userInfo = res.userInfo;

        that.setData({
          userInfo: that.data.userInfo,
          // days: ["2019-08-14","2019-08-15","2019-08-16","2019-08-17","2019-08-18","2019-08-19","2019-08-20","2019-08-21","2019-08-22","2019-08-23","2019-08-24","2019-08-25","2019-08-26","2019-08-27"]
        })


      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  goMiniprogram: function () {
    wx.navigateToMiniProgram({
      appId: 'wxa2750e1d9cc124d1',
      path: 'pages/landingPage/landingPage?code=EOSS-SS20',
      success(res) {
        // 打开成功
        console.log(res)
      },
      fail(res) {
        console.log(res)
      },
      complete(res) {
        console.log(res)
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var that = this;
    let unionid = wx.getStorageSync(storage.keys.unionid);

    wx.request({
      url: constant.api(app.globalData.pord).url + '/profile?unionid=' + unionid,
      method: 'GET',
      dataType: 'json',
      responseType: 'text',
      success: function (res) {
        if (res.data.code == "0") {
          console.log(res.data.data)
          if (res.data.data.student) {
            that.setData({
              user: res.data.data.user,
              agent: res.data.data.agent,
              student: res.data.data.student,
              courseRoundCount: res.data.data.courseRoundCount,
              vip: res.data.data.vip,
              card: res.data.data.card,
              cardId: res.data.data.cardId,
              survey: res.data.data.survey,
              courseSchedules: res.data.data.courseSchedules,
              username: res.data.data.user.profile.nickname,
              img: res.data.data.user.profile.avatar,
              student_id: res.data.data.student.id,

            });
            if(res.data.data.hasCoupon && (res.data.data.hasCoupon == "true" || res.data.data.hasCoupon == true)) {
              that.setData({
                hasCoupon: true
              })
            }

            if(res.data.data.card && res.data.data.card != null && res.data.data.card != "" && res.data.data.card != "null") {
              that.setData({
                showCard: true
              })
            }

            wx.request({
              url: constant.api(app.globalData.pord).url + '/xh/api/user/get_date/',
              method: 'POST',
              data: {
                // coach_id: that.data.coach_id,
                // date: that.data.chooseDay,
                union_id: unionid
              },
              dataType: 'json',
              responseType: 'text',
              header: {
                "Content-Type": "application/x-www-form-urlencoded"
              },
              success: function (res) {
                that.setData({
                  days: res.data,
                });
                console.log(res.data)
                var i;
                var tmp = false;

                for (i = 0; i < res.data.length; i++) {
                  console.log(res.data[i].a)
                  // text += cars[i] + "<br>";
                  if (res.data[i].a == 1) {
                    tmp = true;
                  }
                }
                if (tmp) {
                  that.setData({
                    days_true: true,
                  });
                } else {
                  that.setData({
                    days_true: false,
                  });
                }


              },
              fail: function (res) {
                wx.showToast({
                  title: '请求数据失败',
                  icon: 'none',
                  duration: 1000
                });
              }
            })

          } else {
            that.setData({
              user: res.data.data.user,
              agent: res.data.data.agent,
              student: res.data.data.student,
              courseRoundCount: res.data.data.courseRoundCount,
              vip: res.data.data.vip,
              survey: res.data.data.survey,
              courseSchedules: res.data.data.courseSchedules,
              username: res.data.data.user.profile.nickname,
              img: res.data.data.user.profile.avatar
            });
          }


          if (that.data.user.mobile && that.data.user.mobile != wx.getStorageSync(storage.keys.mobile)) {
            store.setSync(storage.keys.mobile, that.data.user.mobile, function () {}, function () {});
          }
        } else {
          wx.showToast({
            title: res.data.message ? res.data.message : '请求失败',
            icon: 'none',
            duration: 3000,
            mask: true
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '加载数据失败',
          icon: 'none',
          duration: 3000,
          mask: true
        })
      }
    })
    if (that.data.student_id) {
      wx.request({
        url: constant.api(app.globalData.pord).url + '/xh/api/user/get_date/',
        method: 'POST',
        data: {
          // coach_id: that.data.coach_id,
          // date: that.data.chooseDay,
          union_id: unionid
        },
        dataType: 'json',
        responseType: 'text',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        success: function (res) {
          that.setData({
            days: res.data,
          });
          console.log(res.data)
          var i;
          var tmp = false;

          for (i = 0; i < res.data.length; i++) {
            console.log(res.data[i].a)
            // text += cars[i] + "<br>";
            if (res.data[i].a == 1) {
              tmp = true;
            }
          }
          if (tmp) {
            that.setData({
              days_true: true,
            });
          } else {
            that.setData({
              days_true: false,
            });
          }


        },
        fail: function (res) {
          wx.showToast({
            title: '请求数据失败',
            icon: 'none',
            duration: 1000
          });
        }
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})